<template>
	<view class="">
		<wd-search v-model="searchValue" @search="handlesearch" hide-cancel placeholder-left placeholder="请输入关键字">
			<template #prefix>
				<wd-popover mode="menu" :content="menu" @menuclick="handleSearchChange">
					<view class="search-type">
						<text>{{ searchType }}</text>
						<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
					</view>
				</wd-popover>
			</template>
		</wd-search>
		<wd-message-box />
		<wd-toast />
		<wd-tabs v-model="activeTab" auto-line-width @change="handleTabChange">
			<wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.label" :name="tab.value"
				:badge-props="tab.badgeProps">
				<view class="px-1 py-1">
					<wd-table :data="list[tab.value]" :height="600" :border="false">
						<wd-table-col v-for="(col, index) in columns[tab.value]" :key="index" :prop="col.prop"
							:label="col.label" :width="col.width || '100'" :align="col.align || 'center'">
							<template #value="{ row }">
								<template v-if="col.prop.includes('.')">
									<!-- 如果是嵌套属性，拆分路径并按路径访问数据 -->
									{{ getNestedValue(row, col.prop) || '-' }}
								</template>
								<template v-else-if="col.isTag">
									<wd-tag custom-class="space" type="primary">
										{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
									</wd-tag>
								</template>
								<template v-else>
									{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
								</template>
							</template>
						</wd-table-col>
						<wd-table-col prop="grade" label="操作" width="120" fixed align="center">
							<template #value="{ row }">
								<span class="px-1">
									<wd-button type="text" @click="handleDetail(row)">
										{{ tab.value === 'todo' ? '办理' : '查看' }}
									</wd-button>
								</span>
							</template>
						</wd-table-col>
					</wd-table>
				</view>
			</wd-tab>
		</wd-tabs>
		<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
			@update:pageNo="changePage" />
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, nextTick } from 'vue'
	import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
	import { useMessage, useToast } from 'wot-design-uni'
	import * as VehicleInCity from '@/api/oa/vehicleout/inCity'
	import * as VehicleOutCity from '@/api/oa/vehicleout/outCity'
	import * as TaskApi from '@/api/bpm/task'
	import * as ProcessInstanceApi from '@/api/bpm/processInstance'
	import { formatPast2, formatDate } from '@/utils/formatTime'
	import { getNestedValue } from '@/utils/fileUtils'


	const message = useMessage()
	const toast = useToast()



	//存储数据
	const list = ref<any>({
		todo: [],  // 用于存储待办任务列表
		done: [],   // 用于存储已完成任务列表
		copy: [],   // 用于存储流程副本列表
	})
	// 表单列配置项
	const columns = {
		todo: [
			{ prop: 'processInstance.name', label: '流程', width: 140 },
			// { prop: 'processInstance.startUser.nickname', label: '发起人' },
			{ prop: 'name', label: '当前任务', width: 140 },
			// { prop: 'createTime', label: '发起时间', width: 160, format: (val : any) => (formatDate(val)) },
		],
		done: [
			{ prop: 'processInstance.name', label: '流程', width: 120 },
			// { prop: 'processInstance.startUser.nickname', label: '发起人' },
			{ prop: 'name', label: '当前任务', width: 120 },
			// { prop: 'createTime', label: '任务开始时间', width: 160, format: (val : any) => (formatDate(val)) },
			// { prop: 'endTime', label: '任务结束时间', width: 160, format: (val : any) => (formatDate(val)) },
			{
				prop: 'status',
				label: '审批状态',
				align: 'center',
				width: 70,
				format: (val : any) => (getDict(DICT_TYPE.BPM_TASK_STATUS, val)),
				isTag: true
			},
			// { prop: 'reason', label: '审批建议', width: 180 },
			// {
			// 	prop: 'durationInMillis',
			// 	label: '耗时',
			// 	width: 120,
			// 	format: (val : any) => (formatPast2(val)),
			// },
		],
		copy: [
			{ prop: 'processInstanceName', label: '流程名', width: 140 },
			{ prop: 'startUserName', label: '发起人' },
			// { prop: 'processInstanceStartTime', label: '发起时间', width: 160, format: (val : any) => (formatDate(val)) },
			{ prop: 'taskName', label: '抄送任务' },
			{ prop: 'creatorName', label: '抄送人' },
			// { prop: 'createTime', label: '抄送时间', width: 160, format: (val : any) => (formatDate(val)) },
		]
	} as any
	const activeTab = ref('todo')
	const tabs = ref([
		{
			label: '个人待办',
			value: 'todo',
			api: TaskApi.getTaskTodoPage,
			formatFields: { createTime: 'formatDate' },
			badgeProps: {
				modelValue: 0,
				right: '-8px',
				top: '-4px'
			}
		},
		{
			label: '个人已办',
			value: 'done',
			api: TaskApi.getTaskDonePage,
			formatFields: { createTime: 'formatDate', endTime: 'formatDate' },
			badgeProps: {
				modelValue: 0,
				right: '-6px',
				top: '-4px'
			}
		},
		{
			label: '抄送我的',
			value: 'copy',
			api: ProcessInstanceApi.getProcessInstanceCopyPage,
			formatFields: {
				createTime: 'formatDate',
				processInstanceStartTime: 'formatDate',
			},
			badgeProps: {
				modelValue: 0,
				right: '-8px',
				top: '-4px'
			}
		},
	])

	// 查询参数
	const queryParams = ref<any>({
		pageNo: 1,
		pageSize: 10,
		name: '',
		processInstanceName: '',

	})
	const total = ref(0)
	const loading = ref(false)

	const searchType = ref<string>('流程名')
	const searchValue = ref<string>('')
	const menu = ref<any[]>([
		{
			content: '流程名',
			prop: 'processInstanceName'
		}
	])
	
	const handleTabChange = async (value : any) => {
		searchValue.value = ''
		queryParams.value.name = undefined;
		queryParams.value.processInstanceName = undefined;
		await nextTick();
		fetchList();

	}
	function handleSearchChange({ item } : { item : any }) {
		searchType.value = item?.content
	}
	const handlesearch = () => {
		// 找到选中的搜索字段
		const selectedMenu = menu.value.find(item => item.content === searchType.value);
		if (selectedMenu) {
			// 清空之前的搜索条件
			queryParams.value.processInstanceName = undefined;
			queryParams.value.processInstanceName = undefined;
			// 根据选中的搜索类型设置搜索值
			if (activeTab.value === 'todo' || activeTab.value === 'done') {
				console.log('daiban');
				queryParams.value.processInstanceName = searchValue.value.trim()
			} else {
				console.log('其他');
				queryParams.value.processInstanceName = searchValue.value.trim()
			}
			// queryParams.value[selectedMenu.prop] = value.value.trim();
			// 重新获取数据
			fetchList();
		}
	};

	const getDict = (type : any, value : any) => {
		const dicts = getIntDictOptions(type)
		const dict = dicts.find(item => item.value === value)
		return dict ? dict.label : '待审批'
	}
	// 切换分页
	const changePage = (newPage : any) => {
		queryParams.value.pageNo = newPage
		fetchList()
	}
	// 通用字段格式化方法
	function applyFieldFormatters(
		item : any,
		fieldMap : Partial<Record<string, string>> // 👈 允许 key 是可选的
	) {
		const result = { ...item };
		for (const key in fieldMap) {
			const formatter = fieldMap[key];
			if (formatter === 'formatDate') {
				result[key] = formatDate(result[key]);
			} else if (formatter === 'timeConsuming') {
				result[key] = formatPast2(result[key]);
			}
			// 可扩展支持其他 formatter
		}
		return result;
	}
	// 获取单个 tab 数据
	const fetchList = async () => {
		const currentTab = tabs.value.find(t => t.value === activeTab.value);
		if (!currentTab) return;

		loading.value = true;
		try {
			const response = await currentTab.api(queryParams.value);
			list.value[activeTab.value] = response.list
			console.log('list.value', list.value);
			total.value = response.total;
			currentTab.badgeProps.modelValue = response.total;
		} catch (error) {
			console.error(error);
		} finally {
			loading.value = false;
		}
	};
	// 获取所有 tab 数据
	const fetchAllList = async () => {
		loading.value = true;
		try {
			const responses = await Promise.all(
				tabs.value.map(config => config.api(queryParams.value))
			);

			responses.forEach((response:any, index:any) => {
				const config = tabs.value[index];
				list.value[config.value] = response.list
				config.badgeProps.modelValue = response.total;
			});

			total.value = responses[0]?.total ?? 0;
		} catch (error) {
			console.error(error);
		} finally {
			loading.value = false;
		}
	};
	/** 办理按钮 */
	const handleDetail = async (row : any) => {
		console.log('row', row);
		const data = await ProcessInstanceApi.getProcessInstance(row.processInstanceId)
		console.log('data', data);
		const path = data.processDefinition.formCustomViewPath
		const url = `/pagesPackage${path}?processInstanceId=${row.processInstanceId}&id=${data.businessKey}`
		uni.navigateTo({
			url: url
		});
	}
	// 生命周期
	onMounted(() => {
		fetchAllList()
	})
</script>

<style scoped lang="scss"></style>